﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Collections;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

/// <summary>
/// Summary description for RolledUpBiz
/// </summary>
public class RolledUpBiz
{
    //DataSet _dsMonthly = (System.Data.DataSet)HttpContext.Current.Cache["ACC_STATS_YR_MN"];
    //DataSet _dsDaily = (System.Data.DataSet)HttpContext.Current.Cache["ACC_STATS_YR_MN_DY"];

    public RolledUpBiz(string psRollUPType)
    {
        RollUpType = psRollUPType;
        if (HttpContext.Current.Session["SalesDate"] != null)
            ReportDate = ((DateTime)HttpContext.Current.Session["SalesDate"]);
        else
            ReportDate = DateTime.Today.AddDays(-1);
    }

    public RolledUpBiz()
    {
        if (HttpContext.Current.Session["SalesDate"] != null)
            ReportDate = ((DateTime)HttpContext.Current.Session["SalesDate"]);
        else
            ReportDate = DateTime.Today.AddDays(-1);
    }

    string _RollUpType;
    public string RollUpType
    {
        get { return _RollUpType; }
        set { _RollUpType = value; }
    }

    string _RollUpFor;
    public string RollUpFor
    {
        get { return _RollUpFor; }
        set { _RollUpFor = value; }
    }

    private decimal _PriorMonthTotalNetPerDay;
    public decimal PriorMonthTotalNetPerDay
    {
        get { return _PriorMonthTotalNetPerDay; }
        set { _PriorMonthTotalNetPerDay = value; }
    }

    private DateTime _ReportDate;
    public DateTime ReportDate
    {
        get { return _ReportDate; }
        set { _ReportDate = value; }
    }


    public DataView DailyDetail(string psRowFilter, string OFFSET)
    {
        //DataTable dt = ((System.Data.DataTable)HttpContext.Current.Cache["SCORE_STATS_YR_MN_DY." + RollUpType.ToUpper()]);
        string sTable = "SCORE_STATS_YR_MN_DY." + RollUpType.ToUpper();
        DataTable dt = SQLServer.GetDataTable(sTable, psRowFilter);
        if (dt == null)
            return new DataView();
        else
        {
            //dt.DefaultView.RowFilter = psRowFilter;
            DataView dv = dt.DefaultView;

            //DataView dv = (new RolledUpBiz(ROLLUPTYPE)).DailyChartData(SQLFILTER);
            dv.Sort = "DY";

            //Add a datapoint for each day in the selected month, up to yesterday's date
            DateTime dtReport = ReportDate.AddMonths(-Convert.ToInt32(OFFSET));
            int nDays = OFFSET == "0" ? ReportDate.Day : DateTime.DaysInMonth(dtReport.Year, dtReport.Month);

            for (int i = 1; i <= nDays; i++)
            {
                int r = dv.Find(i);
                if (r == -1)
                {
                    DataRowView drv = dv.AddNew();
                    drv["MN"] = dtReport.Month;
                    drv["DY"] = i;
                    drv["IPTV_IN"] =
                    drv["IPTV_OUT"] =
                    drv["IPTV_NET"] =
                    drv["HSIA_IN"] =
                    drv["HSIA_OUT"] =
                    drv["HSIA_NET"] =
                    drv["VOIP_IN"] =
                    drv["VOIP_OUT"] =
                    drv["VOIP_NET"] = 0;
                    drv[RollUpType] = RollUpFor;
                    drv.EndEdit();
                }

            }

            return dv;
        }


    }


    public DataView MonthlyRaw(string psRowFilter)
    {
        DataView dv = new DataView();

        //DataTable dt = ((System.Data.DataTable)HttpContext.Current.Cache["SCORE_STATS_YR_MN." + RollUpType.ToUpper()]);
        string sTable = "SCORE_STATS_YR_MN." + RollUpType.ToUpper();
        DataTable dt = SQLServer.GetDataTable(sTable, psRowFilter);
        if (dt != null)
        {
            //dt.DefaultView.RowFilter = psRowFilter;
            dv = dt.DefaultView;
        }
        return dv;

    }


    public DataView MonthlyDetails(string psRowFilter)
    {

        DataView dv = MonthlyRaw(psRowFilter);
        RollUpFor = psRowFilter.Split('=')[1].Trim().Split('\'')[1];

        RollupMetadata meta = (RollupMetadata)HttpContext.Current.Session["RollupMetadata"];

        if (dv.Count > 0 && dv.Count < meta.Dimensions * 13)
            dv = AddMissingMonths(dv);

        return dv;
    }

    private DataView AddMissingMonths(DataView dv)
    {

        object[] oaKeys = { DBNull.Value, DBNull.Value, DBNull.Value, DateTime.Now.Year, DateTime.Now.Month };
        object[] oaPmuKeys = { DBNull.Value, DBNull.Value, DBNull.Value };

        DataView dv2 = new DataView(dv.ToTable());
        RollupMetadata meta = (RollupMetadata)HttpContext.Current.Session["RollupMetadata"];
        meta.CreateLegendText();

        ArrayList alFilter = new ArrayList(meta.LegendText.Split('*'));
        string[] saNewLegendText = meta.LegendText.Split('*');

        DateTime dtReportStarts = ReportDate.AddMonths(-12);
        int nMonths = 12;

        for (int j = alFilter.Count - 1; j >= 0; j--)    //For each dimension permutation
        {
            //Now walk thru the permutation and assign each of it's values to LOCATION, DWELLING or PRODUCT Key
            //First split the legend to get the permutations
            string[] saPermutations = alFilter[j].ToString().Trim().Split(' ');
            ListItem li;
            for (int k = 0; k < saPermutations.Length; k++)
            {
                //look at each permuation
                //if it's a LOCATION add it to the LOCATION slot
                li = meta.ChlNatl.Items.FindByValue(saPermutations[k]); if (li != null) oaKeys[1] = saPermutations[k];
                //if it's a DWELLING add it to the DWELLING slot
                li = meta.ChlUnits.Items.FindByValue(saPermutations[k]); if (li != null) oaKeys[2] = saPermutations[k];
                //if it's a PRODUCT add it to the PRODUCT slot
                li = meta.ChlProducts.Items.FindByValue(saPermutations[k]); if (li != null) oaKeys[0] = saPermutations[k];
            }

            //Remove the legend text for this permutation?
            if (alFilter.Count > 4)
            {
                dv2.Sort = "PRODUCT,LOCATION,DWELLING";
                oaPmuKeys[0] = oaKeys[0];
                oaPmuKeys[1] = oaKeys[1];
                oaPmuKeys[2] = oaKeys[2];
                int rPmu = dv2.Find(oaPmuKeys);
                if (rPmu == -1) meta._saLegendText[j] = "|";
                else meta._saLegendText[j] += "  |";
            }

            dv2.Sort = "PRODUCT,LOCATION,DWELLING,YR,MN";
            for (int i = 0; i <= nMonths; i++)      //For each month
            {
                //Assign year and month
                DateTime dtReportMonth = dtReportStarts.AddMonths(i);

                oaKeys[3] = dtReportMonth.Year;
                oaKeys[4] = dtReportMonth.Month;

                int r = dv2.Find(oaKeys);
                if (r == -1)        //IF no row for the permutation and month
                {

                    //Add a new row
                    DataRowView drv = dv2.AddNew();
                    drv["YR"] = oaKeys[3];
                    drv["MN"] = oaKeys[4];
                    drv["IPTV_IN"] =
                    drv["IPTV_OUT"] =
                    drv["IPTV_NET"] =
                    drv["HSIA_IN"] =
                    drv["HSIA_OUT"] =
                    drv["HSIA_NET"] =
                    drv["VOIP_IN"] =
                    drv["VOIP_OUT"] =
                    drv["VOIP_NET"] =
                    drv["TOT_NET"] = 0;
                    drv["PRODUCT"] = oaKeys[0];
                    drv["DWELLING"] = oaKeys[2];
                    drv["LOCATION"] = oaKeys[1];
                    drv[RollUpType] = RollUpFor;
                    drv.EndEdit();
                }
            }
        }

        HttpContext.Current.Session["RollupMetadata"] = meta;
        return dv2;
    }

    public DataView MonthlyTableData(string psRowFilter)
    {
        DataView dv = MonthlyDetails(psRowFilter);

        //sum the data by 

        //Show 13 0's
        DataTable table = new DataTable();
        table.Columns.Add("YR", typeof(int));
        table.Columns.Add("MN", typeof(int));
        table.Columns.Add("IPTV_IN", typeof(int));
        table.Columns.Add("IPTV_OUT", typeof(int));
        table.Columns.Add("IPTV_NET", typeof(int));
        table.Columns.Add("HSIA_IN", typeof(int));
        table.Columns.Add("HSIA_OUT", typeof(int));
        table.Columns.Add("HSIA_NET", typeof(int));
        table.Columns.Add("VOIP_IN", typeof(int));
        table.Columns.Add("VOIP_OUT", typeof(int));
        table.Columns.Add("VOIP_NET", typeof(int));

        //Create 13 rows of 9 0's
        for (int x = 0; x < 13; x++)
        {
            table.Rows.Add(table.NewRow());
            table.Rows[x]["YR"] = ReportDate.AddMonths(-(12 - x)).Year;
            table.Rows[x]["MN"] = ReportDate.AddMonths(-(12 - x)).Month;
            table.Rows[x]["IPTV_IN"] = 0;
            table.Rows[x]["IPTV_OUT"] = 0;
            table.Rows[x]["IPTV_NET"] = 0;
            table.Rows[x]["HSIA_IN"] = 0;
            table.Rows[x]["HSIA_OUT"] = 0;
            table.Rows[x]["HSIA_NET"] = 0;
            table.Rows[x]["VOIP_IN"] = 0;
            table.Rows[x]["VOIP_OUT"] = 0;
            table.Rows[x]["VOIP_NET"] = 0;
        }

        //Total biz by Col, Yr & Mn
        for (int i = 0; i < dv.Count; i++)
        {
            table.Rows[i % 13]["IPTV_IN"] = (int)table.Rows[i % 13]["IPTV_IN"] + (int)dv[i]["IPTV_IN"];
            table.Rows[i % 13]["IPTV_OUT"] = (int)table.Rows[i % 13]["IPTV_OUT"] + (int)dv[i]["IPTV_OUT"];
            table.Rows[i % 13]["IPTV_NET"] = (int)table.Rows[i % 13]["IPTV_NET"] + (int)dv[i]["IPTV_NET"];
            table.Rows[i % 13]["HSIA_IN"] = (int)table.Rows[i % 13]["HSIA_IN"] + (int)dv[i]["HSIA_IN"];
            table.Rows[i % 13]["HSIA_OUT"] = (int)table.Rows[i % 13]["HSIA_OUT"] + (int)dv[i]["HSIA_OUT"];
            table.Rows[i % 13]["HSIA_NET"] = (int)table.Rows[i % 13]["HSIA_NET"] + (int)dv[i]["HSIA_NET"];
            table.Rows[i % 13]["VOIP_IN"] = (int)table.Rows[i % 13]["VOIP_IN"] + (int)dv[i]["VOIP_IN"];
            table.Rows[i % 13]["VOIP_OUT"] = (int)table.Rows[i % 13]["VOIP_OUT"] + (int)dv[i]["VOIP_OUT"];
            table.Rows[i % 13]["VOIP_NET"] = (int)table.Rows[i % 13]["VOIP_NET"] + (int)dv[i]["VOIP_NET"];
        }


        //return empty
        return table.DefaultView;
    }

    public DataView MonthlyChartData(string psRowFilter, bool pbStacked)
    {
        DataView dv = MonthlyDetails(psRowFilter);

        if (dv.Count == 0 || pbStacked == false)
        {
            //Show 13 0's
            DataTable table = new DataTable();
            table.Columns.Add("YR", typeof(int));
            table.Columns.Add("MN", typeof(int));
            table.Columns.Add("TOT_NET", typeof(int));

            for (int x = 0; x < 13; x++)
            {
                table.Rows.Add(table.NewRow());
                table.Rows[x]["YR"] = ReportDate.AddMonths(-(12 - x)).Year;
                table.Rows[x]["MN"] = ReportDate.AddMonths(-(12 - x)).Month;
                table.Rows[x]["TOT_NET"] = 0;
            }

            if (pbStacked == false)
            { //Total the data
                for (int i = 0; i < dv.Count; i++)
                {
                    table.Rows[i % 13]["TOT_NET"] = (int)table.Rows[i % 13]["TOT_NET"] + (int)dv[i]["TOT_NET"];
                }
            }

            dv = table.DefaultView;
        }


        return dv;
    }

    public DataView DailyTableData(string psRowFilter, string OFFSET)
    {
        RollupMetadata meta = (RollupMetadata)HttpContext.Current.Session["RollupMetadata"];

        RollUpFor = psRowFilter.Split('=')[1].Trim().Split('\'')[1];

        DataView dv = new DataView();

        string sTable = "SCORE_STATS_YR_MN_DY." + RollUpType.ToUpper();
        DataTable dt = SQLServer.GetDataTable(sTable,psRowFilter);
        if (dt != null)
        {
            //dt.DefaultView.RowFilter = psRowFilter;
            dv = dt.DefaultView;

            //if (meta.ChkShowZeroDays.Checked) 
                AddMissingDays(OFFSET, ref dv);
        }

        return dv;
    }

    public DataView DailyChartData(string psRowFilter, string OFFSET)
    {
        //Here we use cumulative totals by day/product so we see the development of the current month's totals
        //We can also show the actual point in the tooltip (or label?)
        RollupMetadata meta = (RollupMetadata)HttpContext.Current.Session["RollupMetadata"];

        RollUpFor = psRowFilter.Split('=')[1].Trim().Split('\'')[1];

        DataView dv = new DataView();

        //DataTable dt = ((System.Data.DataTable)HttpContext.Current.Cache["SCORE_STATS_YR_MN_DY." + RollUpType.ToUpper()]);
        string sTable = "SCORE_STATS_YR_MN_DY." + RollUpType.ToUpper();
        DataTable dt = SQLServer.GetDataTable(sTable,psRowFilter);
        if (dt != null)
        {
            //dt.DefaultView.RowFilter = psRowFilter;
            dv = dt.DefaultView;

            //if (meta.ChkShowZeroDays.Checked) 
                AddMissingDays(OFFSET, ref dv);
            DataView dv2 = new DataView(dv.ToTable());
            if (meta.DailyChartStyle != "Daily") AccumulateDays(ref dv2);
            return dv2;
        }

        return dv;
    }

    private void AddMissingDays(string OFFSET, ref DataView dv)
    {
        //DataView dv = (new RolledUpBiz(ROLLUPTYPE)).DailyChartData(SQLFILTER);
        dv.Sort = "DY";
        //Add a datapoint for each day in the selected month, up to yesterday's date
        DateTime dtReport = ReportDate.AddMonths(-Convert.ToInt32(OFFSET));
        int nDays = OFFSET == "0" ? ReportDate.Day : DateTime.DaysInMonth(dtReport.Year, dtReport.Month);

        for (int i = 1; i <= nDays; i++)
        {
            int r = dv.Find(i);
            if (r == -1)
            {
                DataRowView drv = dv.AddNew();
                drv["YR"] = dtReport.Year;
                drv["MN"] = dtReport.Month;
                drv["DY"] = i;
                drv["IPTV_IN"] =
                drv["IPTV_OUT"] =
                drv["IPTV_NET"] =
                drv["HSIA_IN"] =
                drv["HSIA_OUT"] =
                drv["HSIA_NET"] =
                drv["VOIP_IN"] =
                drv["VOIP_OUT"] =
                drv["VOIP_NET"] = 0;
                drv[RollUpType] = RollUpFor;
                drv.EndEdit();
            }
        }
    }

    private void AccumulateDays(ref DataView dv)
    {
        for (int i = 1; i < dv.Count; i++)
        {
            dv[i]["IPTV_IN"] = (int)dv[i]["IPTV_IN"] + (int)dv[i - 1]["IPTV_IN"];
            dv[i]["IPTV_OUT"] = (int)dv[i]["IPTV_OUT"] + (int)dv[i - 1]["IPTV_OUT"];
            dv[i]["IPTV_NET"] = (int)dv[i]["IPTV_NET"] + (int)dv[i - 1]["IPTV_NET"];
            dv[i]["HSIA_IN"] = (int)dv[i]["HSIA_IN"] + (int)dv[i - 1]["HSIA_IN"];
            dv[i]["HSIA_OUT"] = (int)dv[i]["HSIA_OUT"] + (int)dv[i - 1]["HSIA_OUT"];
            dv[i]["HSIA_NET"] = (int)dv[i]["HSIA_NET"] + (int)dv[i - 1]["HSIA_NET"];
            dv[i]["VOIP_IN"] = (int)dv[i]["VOIP_IN"] + (int)dv[i - 1]["VOIP_IN"];
            dv[i]["VOIP_OUT"] = (int)dv[i]["VOIP_OUT"] + (int)dv[i - 1]["VOIP_OUT"];
            dv[i]["VOIP_NET"] = (int)dv[i]["VOIP_NET"] + (int)dv[i - 1]["VOIP_NET"];
        }
    }

    //public DataView MTD_Sales(string psTracID)
    //{
    //    DataTable dt = _dsMonthly.Tables["MTD_SALES"];
    //    dt.DefaultView.RowFilter = string.Format("TRAC_ID='{0}'", psTracID);
    //    return dt.DefaultView;
    //}
}